#include "base/logging.h"
#include "shop_waiter_list_request.h"

#include <iostream>
#include <sstream>
#include <string>
#include <map>

#include "base/json_escape.h"
#include "im/common/common.h"
#include "im/adapters/recent_contact_adapter.h"
#include "database/scoped_connection.h"
#include "database/simple_db_pool.h"

namespace imserver {
namespace fcgi {


ConfigReader g_config("../conf/im_call_center_admin_service.conf");

bool ShopWaiterListRequest::Response() {
  if (!fcgi_out_) {
    LOG_WARN("null fcgi_out!");
    return false;
  }

  base::SimpleConnectionPool db_conn_pool(g_config.Get("database", "name").c_str(),
                      g_config.Get("database", "server_list").c_str(),
                      g_config.Get("database", "user").c_str(),
                      g_config.Get("database", "password").c_str());

  mysqlpp::ScopedConnection db(db_conn_pool);
  if (!db) {
    LOG_ERROR("CallCenterCache::Reload failed to get a connection from database-pool.");
    return false;
  }

  std::map<int64_t, std::vector<int64_t> > waiter_shops;
  std::map<int64_t, std::vector<int64_t> > shop_waiters;

  mysqlpp::Query query(db->query());
  query << "SELECT shop, waiter FROM shop_waiters";

  try {
    mysqlpp::UseQueryResult ret = query.use();
    if (ret) {
      while(mysqlpp::Row row = ret.fetch_row()) {
        // TODO: 优化性能
        waiter_shops[row["waiter"]].push_back(row["shop"]);
        shop_waiters[row["shop"]].push_back(row["waiter"]);

        LOG_DEBUG("ShopWaiterMap::Reload load shop " << row["shop"]
                  << " waiter=" << row["waiter"]);
      }
    }
  } catch (mysqlpp::Exception& e) {
    LOG_ERROR("ShopWaiterMap::Reload " << query.str() << " EXEC ERROR.(" << e.what() << ")");
    return false;
  }
  LOG_INFO("ShopWaiterMap::Reload ok, waiter_shops.size=" << waiter_shops.size())

  std::stringstream rsp_header;
  rsp_header << "Content-type: text/javascript; charset=utf-8\r\n" << "\r\n";
  FCGX_PutS(rsp_header.str().c_str(), fcgi_out_);

  std::stringstream rsp_body;
  rsp_body << "[";
  if (false) {
    std::map<int64_t, std::vector<int64_t> >::const_iterator it = waiter_shops.begin();
    int waiter_count = 0;
    for(; it != waiter_shops.end(); ++it) {
      if (waiter_count++ > 0) {
        rsp_body << ',';
      }
      rsp_body << "{\"waiter\":" << it->first << ", \"shops\":[";
      int shop_count = 0;
      for(size_t i = 0; i < it->second.size(); ++i) {
        if (shop_count++ > 0) {
          rsp_body << ',';
        }
        rsp_body << it->second[i];
      }
      rsp_body << "]}";
    }
  } else {
    std::map<int64_t, std::vector<int64_t> >::const_iterator it = shop_waiters.begin();
    int shop_count = 0;
    for(; it != shop_waiters.end(); ++it) {
      if (shop_count++ > 0) {
        rsp_body << ',';
      }
      rsp_body << "{\"shop\":" << it->first << ", \"waiters\":[";
      int waiter_count = 0;
      for(size_t i = 0; i < it->second.size(); ++i) {
        if (waiter_count++ > 0) {
          rsp_body << ',';
        }
        rsp_body << it->second[i];
      }
      rsp_body << "]}";
    }
  }
  rsp_body << "]";

  LOG_DEBUG("ShopWaiterListRequest rsp=" << rsp_body.str());

  FCGX_PutS(rsp_body.str().c_str(), fcgi_out_);
  return true;
}

}
}


